package tx.os3.clientserver.client.handlers;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import tx.os3.clientserver.client.connection.ProtocolAdapter;
import tx.os3.clientserver.client.model.FileListModel;

public class UICommandHandler {

    private ProtocolAdapter adapter;

    public UICommandHandler(ProtocolAdapter adapter) {
        if(adapter == null) {
            throw new IllegalArgumentException("Adapter canot be null.");
        }
        this.adapter = adapter;
    }

    public void handleInfoCommand() {
        this.adapter.getServerInfo();
    }

    /**
     * Handles directory listing command for the given directory.
     * 
     * @param dir
     *            Directory name, null or empty string for root dir.
     */
    public void handleDirCommand(String dir) {
        this.adapter
        .listDir((dir == null || dir.isEmpty()) ? FileListModel.ROOT
                : dir);
    }

    public void handlePutCommand(File file) {
        if(file != null) {
            try {
                File createFile = new File(FileListModel.WEBDIR + FileListModel.getInstance().getCurrentDir() + "/" + file.getName());
                FileUtils.copyFile(file, createFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            this.adapter.put(file);
        }
    }

    public void handleDeleteCommand(String fileName) {
        if(fileName != null) {
            try {
                File file = new File(FileListModel.WEBDIR + FileListModel.getInstance().getCurrentDir() + "/" + fileName);
                if(file.exists()) {
                    FileUtils.forceDelete(file);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            this.adapter.delete(fileName);
        }
    }

    public void handleRenameCommand(String fileName, String newFileName) {
        if(fileName != null && newFileName != null) {
            File file = new File(FileListModel.WEBDIR + FileListModel.getInstance().getCurrentDir() + "/" + fileName);
            if(file.exists()) {
                File newFile = new File(FileListModel.WEBDIR + FileListModel.getInstance().getCurrentDir() + "/" + newFileName);
                if(newFile.exists()) {
                    return;
                }
                file.renameTo(newFile);
            }
            this.adapter.rename(fileName, newFileName);
        }
    }

    public void handleDisconnectCommand() {
        this.adapter.disconnect();
    }

    public void handleConnectCommand() {
        this.adapter.connect();
        this.handleDirCommand(null);
    }

    public void handleGetCommand(String fileName) {
        this.adapter.get(fileName);
    }

    public void handleSyncCommand() {
        this.adapter.sync();
    }

}
